package com.zg.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zg.pojo.Tag;
import com.zg.service.TagService;

@Controller
@RequestMapping("/tag")
public class TagController {
	@Resource
	private TagService tagService;
	
	@RequestMapping(value="/addtag", method=RequestMethod.GET)
	public String addTagForm(HttpServletRequest request, Model model) {
		return "tag/addTag";
	}
	
	@RequestMapping(value="/addtag", method=RequestMethod.POST)
	public String addTag(HttpServletRequest request, Model model) {
		String name = new String(request.getParameter("name"));
		String description = new String(request.getParameter("description"));
		
		Tag tag = new Tag();
		
		tag.setDescription(description);
		tag.setName(name);
		
		this.tagService.insert(tag);
		
		return "redirect:/tag/listtag";
	}
	
	@RequestMapping("listtag")
	public String listTag(HttpServletRequest request, Model model) {
		List<Tag> tags;		
		tags = this.tagService.getAll();	
		model.addAttribute("list", tags);
		return "tag/listTag";
	}
	
	@RequestMapping(value="/edittag", method=RequestMethod.GET)
	public String editTagForm(HttpServletRequest request, Model model) {
		int id = new Integer(request.getParameter("id"));
		
		Tag tag = new Tag();
		
		tag = this.tagService.getTagById(id);
		model.addAttribute("tag", tag);
		
		return "tag/editTag";
	}
	
	@RequestMapping(value="/edittag", method=RequestMethod.POST)
	public String editTag(HttpServletRequest request, Model model) {
		int id = new Integer(request.getParameter("id"));
		String name = new String(request.getParameter("name"));
		String description = new String(request.getParameter("description"));
		Tag tag = new Tag();
		tag = this.tagService.getTagById(id);
		tag.setDescription(description);
		tag.setName(name);
		this.tagService.updatePrimaryKeySelective(tag);
		return "redirect:/tag/listtag";
	}
}
